package org.restql.db.operation;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.restql.db.Utility;
import org.restql.db.resource.DatabaseResource;
import org.restql.db.resource.ModifiableDatabaseResource;
import org.restql.db.resource.RequestResource;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DatabaseInsert extends DatabasePutPost {

	private static Log logger = LogFactory.getLog(DatabaseInsert.class);

	public DatabaseInsert(DatabaseResource databaseResource, RequestResource requestResource) {
		super(databaseResource, requestResource);
	}

	// Node containing children of fields to insert
	protected void doOperation(Node updateNode) throws SQLException {
		NodeList fields = updateNode.getChildNodes();
		List<String> fieldList = new ArrayList<String>();
		List<String> valuesList = new ArrayList<String>();
		for (int i = 0; i < fields.getLength(); i++) {
			if (fields.item(i).getNodeType() == Node.ELEMENT_NODE) {
				fieldList.add(fields.item(i).getNodeName());
				valuesList.add(fields.item(i).getTextContent());
			}
		}

		String constructedSQL =
			((ModifiableDatabaseResource) this.databaseResource).getInsertString(this.requestResource) +
			" (" + Utility.commas(fieldList) +
			") values (" + Utility.commasAndQuotes(valuesList) + ")";

		PreparedStatement stmt =
			getConnection().prepareStatement(constructedSQL);

		logger.info("Executing: " + constructedSQL);
		stmt.executeUpdate();
	}

}
